//
//  MyViewController.m
//  financial
//
//  Created by Apple on 2017/9/21.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "MyViewController.h"
#import "LoginViewController.h"
#import "UserIconView.h"
//#import "ScanScanViewController.h"
#import "MyViewCell.h"
//#import "UserCountCell.h"
#import "SubAnalysisViewController.h"
#import "SettingViewController.h"
#import "MessageViewController.h"
#import "FaceBookViewController.h"
#import "InviteViewController.h"
#import "ChangeInfoViewController.h"
#import "MyPointViewController.h"

static NSString * myCellID = @"MyViewCellID";
//static NSString * userCellID = @"UserCountCellID";
@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
//@property (nonatomic, strong) UIButton    * leftBtn;
@property (nonatomic, strong) UIView      * bgView;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) UserIconView* headView;
@property (nonatomic, strong) NSArray     * dataArray;
@end

@implementation MyViewController
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BGColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"MyViewCell" bundle:nil] forCellReuseIdentifier:myCellID];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 44;
    }
    return _tableView;
}
- (UIView *)headView
{
    if (!_headView) {
        _headView = [[UserIconView alloc] init];
        _headView.backgroundColor = BARColor;
    }
    return _headView;
}
- (void)networking
{
    WeakSelf
    [HttpRequest postWithURLString:HOST(@"app/user/home") parameters:nil showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            [HFUser rememberUsername:responseObject[@"data"][@"username"]];
            [HFUser rememberNickName:responseObject[@"data"][@"nickName"]];
            [weakSelf saveIcon:responseObject[@"data"][@"avatar"]];
        }
    } failure:^(NSError * _Nullable error) {
        
    }login:^(BOOL isLogin) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf ShowLoginView];
        });
    }];
}
- (void)ShowLoginView
{
    HFLoginView * logView = [HFLoginView shareInit];
    [logView show];
    WeakSelf
    logView.clickPushBlock = ^(NSInteger index) {
        if (index == 0) {
            [weakSelf PushRigest];
        }else{
            [weakSelf PushLogin];
        }
    };
}
- (void)PushRigest
{
    RegisterViewController * rc = [[RegisterViewController alloc] init];
    rc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rc animated:YES];
}
- (void)PushLogin
{
    WeakSelf
    LoginViewController * lgvc = [[LoginViewController alloc] init];
    lgvc.myClass = NSStringFromClass([self class]);
    lgvc.hidesBottomBarWhenPushed = YES;
    lgvc.LoginSuccessBlock = ^{
        [weakSelf.headView setDataWithUserIcon];
    };
    [self.navigationController pushViewController:lgvc animated:YES];
}

- (void)saveIcon:(NSString *)image
{
    WeakSelf
    dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL); // 创建GCD线程队列
    dispatch_async(xrQueue, ^{
        // 异步下载图片
        UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:image]]];
        // 主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *path_document = NSHomeDirectory();
            //设置一个图片的存储路径
            NSString *imagePath = [path_document stringByAppendingString:@"/Documents/icon.png"];
            //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
            [UIImagePNGRepresentation(img) writeToFile:imagePath atomically:YES];
            [weakSelf.headView setDataWithUserIcon];
        });
    });
}
- (NSArray *)dataArray
{
    if (!_dataArray) {
//        @[@[@"0.00",@"0.00",@"0.00"]],
//        @{@"image":@"my_collection",@"title":@"我的收藏"},
        _dataArray = @[@[@{@"image":@"my_feng",@"title":@"我的积分"},
                         @{@"image":@"my_friend",@"title":@"邀请新用户"}],
                       @[@{@"image":@"my_message",@"title":@"消息通知"},
                         @{@"image":@"my_fack",@"title":@"意见反馈"},
                         @{@"image":@"my_set",@"title":@"设置"}]];
    }
    return _dataArray;
}

- (void)setNavBar
{
    [self setHideBackBtn:YES];    
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = @"我的";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBar];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.barView.mas_bottom).offset(0);
    }];
    self.bgView = [UIView new];
    [self.headView addSubview:self.bgView];
    self.bgView.backgroundColor = BARColor;
    
    self.tableView.tableHeaderView = self.headView;
    [self.headView setDataWithUserIcon];
    if ([[HFUser getSaveToken] length] > 0) {
        [self networking];
    }
    WeakSelf
    self.headView.LoginBlock = ^{
        [weakSelf PushLogin];
    };
    self.headView.ClickBlock = ^(NSInteger index) {
        if ([[HFUser getSaveToken] length] > 0) {
            ChangeInfoViewController * cv = [[ChangeInfoViewController alloc] init];
            cv.hidesBottomBarWhenPushed = YES;
            cv.ClickChangeInfoBlock = ^{
                [weakSelf.headView setDataWithUserIcon];
            };
            [weakSelf.navigationController pushViewController:cv animated:YES];
        }else{
            [weakSelf PushLogin];
        }
    };
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networking) name:LOGINSUCCESS object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networking) name:FORGETLOGINSUCCESS object:nil];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.bgView setFrame:CGRectMake(0, 0, SCREENWIDTH, scrollView.contentOffset.y)];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.bgView setFrame:CGRectMake(0, 0, SCREENWIDTH, scrollView.contentOffset.y)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [self.dataArray[section] count];
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyViewCell * myCell = (MyViewCell *)[tableView dequeueReusableCellWithIdentifier:myCellID];
    myCell.selectionStyle = UITableViewCellSelectionStyleNone;
    [myCell setDataWithDict:self.dataArray[indexPath.section][indexPath.row]];
    return myCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[HFUser getSaveToken] length] == 0) {
        [self ShowLoginView];
        return;
    }
    switch (indexPath.section) {
        case 0:
        {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            switch (indexPath.row) {
                case 0:
                {
                    MyPointViewController * mv = [[MyPointViewController alloc] init];
                    mv.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:mv animated:YES];
                }
                    break;
                case 1:
                {
                    InviteViewController * iv = [[InviteViewController alloc] init];
                    iv.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:iv animated:YES];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
        {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            switch (indexPath.row) {
//                case 0: //关注
//                {
//                    SubAnalysisViewController *sv = [[SubAnalysisViewController alloc] init];
//                    sv.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:sv animated:YES];
//                }
//                    break;
                case 0:
                {
                    MessageViewController * mv = [[MessageViewController alloc] init];
                    mv.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:mv animated:YES];
                }
                    break;
                case 1://意见
                {
                    FaceBookViewController * fv = [[FaceBookViewController alloc] init];
                    fv.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:fv animated:YES];
                }
                    break;
                default:
                {
                    WeakSelf
                    SettingViewController * sv = [[SettingViewController alloc] init];
                    sv.hidesBottomBarWhenPushed = YES;
                    sv.clickLogOut = ^{
                        [weakSelf.headView setDataWithUserIcon];
                    };
                    [self.navigationController pushViewController:sv animated:YES];
                }
                    break;
            }
        }
            break;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
//    if (section == 0) {
//        view.frame = CGRectMake(0, 0, SCREENWIDTH, 40);
//        view.backgroundColor = [UIColor whiteColor];
//        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREENWIDTH - 30, 39)];
//        label.font = CONTENTFONT;
//        label.textColor = TEXTColor;
//        label.text = @"我的持仓";
//        [view addSubview:label];
//        UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(SCREENWIDTH - 20, 15.5, 5, 9)];
//        imageV.image = [UIImage imageNamed:@"right_jian"];
//        [view addSubview:imageV];
//    }else{
//        view.frame = CGRectMake(0, 0, SCREENWIDTH, 0);
//    }
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.f;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
